package com.lzb.provideb;

import android.Manifest;
import android.content.ContentResolver;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private TextView txt;
    public static final String SCHEME = "content"; // 源码里面规定这样写，所以这个地方改变不了
    public static final String HOST = "com.lzb.provide.myContentProvide";
    public static final String PATH = "students/7";
    public static String STUDENT_ID = "studentId";
    public static String MESSAGE = "message";

    public static final Uri CONTENT_URI = Uri.parse(SCHEME + "://" + HOST +  "/" + PATH);
    private ContentResolver contentResolver;
    public static final String TAG = MainActivity.class.getSimpleName();
    private Handler handler  = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == 0x123){
                Toast.makeText(MainActivity.this, "数据发生变化", Toast.LENGTH_SHORT).show();
            }
            return false;
        }
    });


    /** 内容提供者监听类 */
    private ContentObserver contentObserver = new ContentObserver(handler) {
        @Override
        public boolean deliverSelfNotifications() {
            Log.i(TAG ,"deliverSelfNotifications");
            return super.deliverSelfNotifications();
        }

        /**
         * ContentProvider的内容发生变化时，触发该方法
         * @param selfChange
         */
        @Override
        public void onChange(boolean selfChange) {
            super.onChange(selfChange);
            Log.i(TAG ,"onChange-------->");
        }
        /**
         * ContentProvider的内容发生变化时，触发该方法  这个与上方法相比多个Uri
         * @param selfChange
         */
        @Override
        public void onChange(boolean selfChange, Uri uri) {
            super.onChange(selfChange, uri);
            Log.i(TAG ,"onChange-------->" + uri);
            handler.sendEmptyMessage(0x123);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        txt = (TextView) findViewById(R.id.txt);
    }


    @Override
    protected void onResume() {
        super.onResume();
        contentResolver = getContentResolver();
        /**
         * 参数：
         * 一 uri：该监听器所要监听的ContentProvide的uri
         * 二 notifyForDescendants：假设注册监听的Uri为 content://abc  notifyForDescendants为 true
         *                          那么Uri为content://abc/lzb、 content://abc/xxx的数据发生变化时，
         *                          也能触发监听器，否则不能触发监听器
         * 三 observer：监听器实例
         */
        contentResolver.registerContentObserver(CONTENT_URI, true, contentObserver);

        //动态申请权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_EXTERNAL_STORAGE},0x234);
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 0x234 ){//应用没有被授权关闭应用
            if (grantResults[0] != 0 || grantResults[1] != 0){
                finish();
            }else {
                Cursor cursor  = contentResolver.query(CONTENT_URI,null,null,null,null);
                if (null != cursor){
                    while (cursor.moveToNext()){
                        int id = cursor.getInt(cursor.getColumnIndex(STUDENT_ID));
                        String message = cursor.getString(cursor.getColumnIndex(MESSAGE));
                        txt.setText("ID=" + id + " ; message=" + message);
                        break;
                    }

                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        contentResolver.unregisterContentObserver(contentObserver);
    }



}
